package cn.zhj.testjs;

import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class JsActivity extends AppCompatActivity implements View.OnClickListener {

    WebView webView;
    Button btn1 , btn2 , btn3 , btn4;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js);
        webView = findViewById(R.id.webview);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);


        WebUtils.setWebSettings(webView);
        webView.setWebChromeClient(new WebChromeClient());//支持js弹出alert
        webView.loadUrl("file:///android_asset/html/js2android.html");
        //此处 AppInterface 即 window.AppInterface.getUserId(para); 的 AppInterface
        webView.addJavascriptInterface(new AndroidJs(this) , "AppInterface");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                webView.loadUrl("javascript:add(1 , 3)");
                break;
            case R.id.btn2:
                webView.evaluateJavascript("javascript:guid()", value -> {
                    Toast.makeText(this , "js返回的uuid == " + value , Toast.LENGTH_SHORT).show();
                });
                break;
            case R.id.btn3:
                String jscode = "javascript:function customAlert() {var b = guid();if(b){alert(b);}}";
                webView.loadUrl(jscode);
                break;
            case R.id.btn4:
                webView.loadUrl("javascript:customAlert()");
                break;
            default:
                break;
        }

    }
}
